<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="45%">
        <el-button type="primary" @click="dialogFormVisible = true">添加类别</el-button>
        <el-button @click="deleteRangeCategory">批量删除</el-button>
        <el-button @click="getData()">刷新</el-button>
        <el-tree style="max-width: 600px" :data="data" show-checkbox default-expand-all :expand-on-click-node="false"
          :render-after-expand="false" check-strictly :default-expanded-keys="data" @check-change="getCategoryId"
          @node-click="handleNodeClick" />

      </el-aside>
      <el-main style="padding:0px;margin-left:20px;width:45%">
        <span>选中类别信息（可修改）</span>
        <hr>
        <el-form ref="ruleFormRefs" style="max-width: 600px" :model="form" label-width="auto">
          <el-form-item label="名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入类型名称" />
          </el-form-item>
          <el-form-item label="编号：" prop="serial_no">
            <el-input v-model="form.serial_no" placeholder="请输入类型编号" />
          </el-form-item>

          <el-form-item label="上级目录：">
            <el-cascader style="width:100%" v-model="categoryIds" @change="shows()" :options="data" :props="props1"
              :show-all-levels="false" clearable />
          </el-form-item>

          <el-form-item label="排序：">
            <el-input v-model="form.sort" />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="form.remark" />
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="resetForms()">恢复初始信息</el-button>
          <el-button type="primary" @click="submitForms()">
            确认修改
          </el-button>
        </div>
      </el-main>
    </el-container>
  </div>

  <el-dialog v-model="dialogFormVisible" title="新增" width="500">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm">
      <el-form-item label="名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入类型名称" />
      </el-form-item>
      <el-form-item label="编号：" prop="serial_no">
        <el-input v-model="ruleForm.serial_no" placeholder="请输入类型编号" />
      </el-form-item>
      <el-form-item label="类别：">
        <el-cascader v-model="categoryId" @change="show()" :options="data" :props="props1" :show-all-levels="false"
          clearable />
      </el-form-item>
      <el-form-item label="排序：">
        <el-input v-model="ruleForm.sort" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { GetMaterialCategoryTree, InsertMaterialCategory, GetMaterialCategoryOne, UpdateMaterialCategoryOne, DeleteMaterialCategoryRange } from '@/api/category/index'
import { type info, type Categoryinfo } from '@/api/category/type'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const bei = ref([])

const getCategoryId = (data: any, checked: any) => {
  if (checked) {
    bei.value.push(data.value as unknown as typeof bei.value[number]);
  } else {
    bei.value = bei.value.filter(item => item !== data.value);
  }
};


const deleteRangeCategory = async () => {
  if (bei.value.length == 0) {
    ElMessage.error("至少选择一项删除")
    return
  }
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await DeleteMaterialCategoryRange(bei.value)
        .then(res => {
          if (res.data.code > 0) {
            ElMessage.success(res.data.message)
            getData()
            getCategoryData()
          } else {
            ElMessage.error(res.data.message)
            return
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作取消',
      })
    })

}

const dialogFormVisible = ref(false)
//修改反填数据取值
const handleNodeClick = (data: any) => {
  localStorage.setItem('categoryId', data.value)
  getCategoryData()
}
const categoryIds = ref([])
const shows = () => {
  if (categoryIds.value != null) {
    form.parent_id = categoryIds.value[categoryIds.value.length - 1]
  } else {
    form.parent_id == null
  }
}
const form = reactive<Categoryinfo>({
  category_id: 0,
  name: '',
  category_level: 0,
  parent_id: null,
  sort: '',
  delete_flag: false,
  serial_no: '',
  remark: '',
  tenant_id: localStorage.getItem('tenant_id')
})
const getCategoryData = async () => {
  let aa = localStorage.getItem('categoryId');
  let categoryId = Number(aa);
  await GetMaterialCategoryOne(categoryId)
    .then(res => {
      form.category_id = res.data.category_id
      form.name = res.data.name
      form.parent_id = res.data.parent_id
      categoryIds.value = res.data.parent_id
      form.remark = res.data.remark
      form.serial_no = res.data.serial_no
      form.sort = res.data.sort
      form.tenant_id = res.data.tenant_id
    })
}

const submitForms = async () => {
  if (form.category_id == 0) {
    ElMessage.error('请选择需要修改的数据信息')
    return
  }
  if (categoryIds.value == null) {
    form.parent_id = 0
  }
  await UpdateMaterialCategoryOne(form)
    .then(function (res) {
      if (res.data.code > 0) {
        ElMessage.success(res.data.message)
        getData()
        getCategoryData()
      } else {
        ElMessage.error(res.data.message)
        return
      }
    })
}

const resetForms = () => {
  getCategoryData()
}


//添加
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<info>({
  categoryId: 0,
  name: '',
  category_level: 0,
  parent_id: null,
  sort: '',
  delete_flag: false,
  serial_no: '',
  remark: '',
  create_time: new Date,
  update_time: null,
  tenant_id: localStorage.getItem('tenant_id')
})

const rules = reactive<FormRules<info>>({
  name: [
    { required: true, message: '名称不能为空', trigger: 'blur' }
  ],
  serial_no: [
    { required: true, message: '编号不能为空', trigger: 'blur' }
  ],
})
const categoryId = ref()
const show = () => {
  ruleForm.parent_id == null
  if (categoryId.value.length > 0) {
    ruleForm.parent_id = categoryId.value[categoryId.value.length - 1]
  } else {
    ruleForm.parent_id == null
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (ruleForm.parent_id == null) {
        ruleForm.parent_id = 0
      }
      await InsertMaterialCategory(ruleForm)
        .then(function (res) {
          if (res.data.code > 0) {
            ElMessage.success(res.data.message)
            getData()
            resetForm()
          } else {
            ElMessage.error(res.data.message)
            return
          }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = () => {
  dialogFormVisible.value = false
  ruleForm.name = ''
  ruleForm.parent_id = null
  ruleForm.sort = ''
  ruleForm.serial_no = ''
  categoryId.value = null
}
const props1 = {
  checkStrictly: true,
}
const data = ref([])
const getData = async () => {
  await GetMaterialCategoryTree().then(function (res) {
    data.value = res.data
  })
}

onMounted(() => {
  getData()
})
</script>